package com.liangtian.mdm.material.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.liangtian.mdm.base.authentication.JWTUtil;
import com.liangtian.mdm.base.constants.ResultCode;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.response.BaseResponse;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.dm.common.pojo.ResponseMsg;
import com.liangtian.mdm.material.model.WlFh;
import com.liangtian.mdm.material.service.WlFhService;
import com.liangtian.mdm.system.log.SysLogUtil;
import com.liangtian.mdm.system.log.model.SysLogEnum;
import com.liangtian.mdm.system.user.util.ExcelImport;
import com.liangtian.mdm.util.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.liangtian.mdm.base.constants.MdmConstant.TABLE_NAME_WLFH;

/**
 * 物料符号Controller
 */

@RestController
@RequestMapping("/wlFhController")
public class WlFhController extends BaseController {

    @Autowired
    private WlFhService wlFhService;

    private ExcelImport excelImport = new ExcelImport();
    private List<WlFh> wlFhListByExport = null;
    private Map<String, Object> wlFhmap = null;

    /**
     * 查询物料符号列表
     * @param request
     * @param wlfh
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @PostMapping(value = "/queryAllWlFhList")
    public BaseResponse queryAllWlFhList(HttpServletRequest request, WlFh wlfh) {
        Map paramMap = RequestUtils.paramToMap(request, WlFh.class, false);
        PageInfo pageInfo = wlFhService.getWlFhListByCond(paramMap);
        List l = pageInfo.getList();
        wlFhListByExport = pageInfo.getList();
        wlFhmap = paramMap;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);// JSONArray
        jsonObject.put("total", pageInfo.getTotal());
        return new BaseResponse().ok(jsonObject);
    }

    /**
     * 物料符号插入
     * @param wlfh
     * @param request
     * @return
     */
    @PostMapping(value = "/insertWlFh")
    public BaseResponse insertWlFh(WlFh wlfh, HttpServletRequest request) {
        // 获取当前日期
        Date date = new Date();
        // 通过JWT工具类获取用户
        String token = (String) SecurityUtils.getSubject().getPrincipal();
        String username = JWTUtil.getUsername(token);
        // 该用户为该物料符号的创建人 user.getUserAccount()
        wlfh.setCreater(username);
        //通过fhname/fhtype查询物料符号是否存在
        int count = wlFhService.getWlFhExist(wlfh);
        if(count > 0){
            return BaseResponse.genResponse(ResultCode.WL_FH_HAS_EXIST);
        }
        wlFhService.insertWlFh(wlfh);
        SysLogUtil.insertLog("新增物料符号["+wlfh.getFhname()+","+wlfh.getFhtype()+"]",
                SysLogEnum.WL_FH.getCode(), SysLogEnum.XZ.getCode(), request);
        return new BaseResponse().ok("新增物料符号成功");
    }

    /**
     * 检查该物料符号是否存在
     * @param wlfh
     * @return
     */
    @PostMapping(value = "/checkWlFhExist")
    public BaseResponse checkWlFhExist(WlFh wlfh){
        HashMap<String, Integer> map = new HashMap<>();
            int count = wlFhService.getWlFhExist(wlfh);
            if (count > 0){
                return BaseResponse.genResponse(ResultCode.WL_FH_HAS_EXIST);
            }else {
                return BaseResponse.genResponse(ResultCode.WL_FH_NOT_EXIST);
            }
//
    }

    /**
     * 根据物料符号ID(WYM)查询
     * @param wlfh
     * @return
     */
    @PostMapping(value = "/selectWlFhById")
    public BaseResponse selectWlFhById(WlFh wlfh){
        String nullArg = CheckNotNullUtils.checkObjNotNull(wlfh,"wym");
        if (nullArg != null) {
            return BaseResponse.genResponse(ResultCode.FAIL_REQ_PARAM_ERROR.getCode(), nullArg + "不能为空");
        }
        WlFh wlFh = wlFhService.getWlFhById(wlfh);
        return new BaseResponse().ok(wlFh);
    }

    /**
     * 物料符号修改
     * @param wlfh：
     * @param request：
     * @return
     */
    @PostMapping(value = "/updateWlFh")
    public BaseResponse updateWlFh(WlFh wlfh, HttpServletRequest request) {
        WlFh wlFh = wlFhService.getWlFhById(wlfh);
        if(wlFh == null ){
            return BaseResponse.genResponse(ResultCode.WL_FH_NOT_EXIST);
        }
           wlFhService.updateWlFh(wlfh);
            SysLogUtil.insertLog("编辑物料符号[" + wlfh.getFhname() + "," + wlfh.getFhtype() + "]",
                    SysLogEnum.WL_FH.getCode(), SysLogEnum.BJ.getCode(), request);
            return new BaseResponse().ok("物料符号修改成功");
        }

    /**
     * 修改时校验物料符号对象是否存在
     * @param wlfh
     * @return
     */
    @RequestMapping(value = "/checkWlFhExistByEdit", method = RequestMethod.POST)
    public BaseResponse checkWlFhExistByEdit(WlFh wlfh) {
        JSONObject jsonObject = new JSONObject();
        int i = wlFhService.checkWlFhExistByEdit(wlfh);
        jsonObject.put("exist", i>0);
        return new BaseResponse().ok(jsonObject);
    }

    /**
     * 批量删除物料符号
     * @param request
     * @return
     */
    @PostMapping(value = "/deleteWlFhByIds")
    public BaseResponse deleteWlFhByIds(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        if (ids == null || "".equals(ids)) {
            return new BaseResponse().fail(ResultCode.DELETE_FAILED.getCode(), "ids为空,无法进行删除");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("idList", ids.split(","));
        int ret = wlFhService.deleteWlFhByIds(map);
        if (ret > 0){
            return new BaseResponse().ok("批量删除物料符号成功");
        }else{
            return new BaseResponse().fail("400","批量删除物料符号失败");
        }
    }

    /**
     * 更新物料符号状态
     * @param wlfh
     * @param request
     * @return
     */
    @PostMapping(value = "/updateWlFhStatus")
    public BaseResponse updateWlFhStatus(WlFh wlfh, HttpServletRequest request) {
        try {
            String nullArg = CheckNotNullUtils.checkObjNotNull(wlfh,"wym", "status");
            if (nullArg != null) {
                return BaseResponse.genResponse(ResultCode.FAIL_REQ_PARAM_ERROR.getCode(), nullArg + "不能为空");
            }
            wlFhService.updateWlFhStatus(wlfh);
            //记录日志
            if (Integer.parseInt(wlfh.getStatus()) == 1) {
                SysLogUtil.insertLog("启用物料符号[" + wlfh.getWym() + "]",
                        SysLogEnum.WL_FH.getCode(), SysLogEnum.QY.getCode(), request);
            } else if (Integer.parseInt(wlfh.getStatus()) == 2) {
                SysLogUtil.insertLog("停用物料符号[" + wlfh.getWym() + "]",
                        SysLogEnum.WL_FH.getCode(), SysLogEnum.TY.getCode(), request);
            }
            return new BaseResponse().ok("更新物料符号状态成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseResponse().fail("400","更新物料符号状态失败");
        }

    }

    /**
     * 查询没有分页的物料符号
     * @param request
     * @param wlfh
     * @return
     */
    @RequestMapping(value = "/getWlFhNoPageByCond", method = RequestMethod.POST)
    public BaseResponse getWlFhNoPageByCond(HttpServletRequest request, WlFh wlfh) {
        List<WlFh> list = wlFhService.getWlFhNoPageByCond(wlfh);
        ResultObject result = new ResultObject(list);
        return new BaseResponse().ok(result);
    }

    /**
     * 批量导入物料符号
     * @param request
     * @param
     * @return
     */
    @RequestMapping(value = "excelImport", method = RequestMethod.POST)
    public BaseResponse excelImport(HttpServletRequest request) {
        BaseResponse baseResponse = new BaseResponse().ok();
        try {
            MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = mulRequest.getFile("excel");
            // 获取路径
            String ctxPath = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator;
            // 创建文件
            File dirPath = new File(ctxPath);
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
            File uploadFile = new File(ctxPath + file.getOriginalFilename());

            // 保存上传的文件到服务器发布项目中的upload文件夹下
            FileCopyUtils.copy(file.getBytes(), uploadFile);

            Workbook book = ExcelImport.getWorkbook(uploadFile);
            // 得到sheet总数
            int sheetNum = book.getNumberOfSheets();
            for (int i = 0; i < sheetNum; i++) {
                Sheet sheet = book.getSheetAt(i);
                List<Object[]> valueList = ExcelImport.read(sheet);
                // 插入数据
                if (CollectionUtils.isNotEmpty(valueList)) {
                    baseResponse = wlFhService.checkImportList(valueList, TABLE_NAME_WLFH);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResponse.genResponse(ResultCode.FAIL);
        }
        return baseResponse;
    }

    /**
     * 导出模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "wlFhExport", method = RequestMethod.GET)
    public void wlFhExport(HttpServletResponse response, HttpServletRequest request) {
        String path = IoUtil.getTemplatePath();
        String fileName = TemplateName.WL_FH_TEMPLATE;//服务器上存的文件名
        String uploadFileName = "物料符号导入模板";//给用户下载看到的文件名
        ExportUtil.exportTemplate(path, fileName, uploadFileName, response);
    }

    /**
     * 导出当前页数据
     */
    @RequestMapping(value = "wlFhExportExcel", method = RequestMethod.POST)
    public void wlFhExportExcel(HttpServletResponse response, HttpServletRequest request) {
        if (CollectionUtils.isNotEmpty(wlFhListByExport)){
            wlFhService.exportWlFh(wlFhListByExport, response);
        }
    }

    /**
     * 导出所有数据
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "wlFhExportExcel2", method = RequestMethod.POST)
    public void wlFhExportExcel2(HttpServletResponse response) {
            PageInfo pageInfo = wlFhService.getWlFhListByCond2(wlFhmap);
            List l = pageInfo.getList();
        if (CollectionUtils.isNotEmpty(l)) {
                wlFhService.exportWlFh(l, response);
            }

    }

    /**
     * 在删除符号前调用，检查该符号是否被物料列表模板所引用
     * @param request
     * @return
     */
    @RequestMapping(value = "/checkLbmbTzlFhByFhWym", method = RequestMethod.POST)
    public BaseResponse checkLbmbTzlFhByFhWym(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            String fhwym = request.getParameter("fhwym");
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("fh_wym", "'" + fhwym + "'");
            int count = this.wlFhService.checkLbmbTzlFhByFhWym(map);
            if (count > 0) {
                return new BaseResponse().fail("400", "此符号已被物料模板使用，不可以删除操作");
            } else {
                return new BaseResponse().ok("可以删除");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseResponse().fail("400", "此符号已被物料模板使用，不可以删除操作");
        }
    }
}
